package com.learn.kafka.util;

import com.google.common.collect.Maps;
import org.apache.log4j.Logger;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
import java.util.Properties;

public class PropertiesUtil {

    private static Logger logger = Logger.getLogger(PropertiesUtil.class.getName());


    private static Properties properties;

    private String proper_resource;

    public void setProper_resource(String proper_resource) {
        this.proper_resource = proper_resource;
    }

    public PropertiesUtil(String proper_resource) {
        this.proper_resource = proper_resource;
    }

    public Map<String, String> getProperties() {
        properties = getInstance();
        try {
            InputStream inputStream = PropertiesUtil.class.getClassLoader().getResourceAsStream(proper_resource);
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String, String> regMap = Maps.newHashMap();
        regMap.put("kafka.producer.batch.size", properties.getProperty("kafka.producer.batch.size"));
        regMap.put("appsecret", properties.getProperty("appsecret"));
        regMap.put("base_url", properties.getProperty("base_url"));
        regMap.put("weixin_token", properties.getProperty("weixin_token"));
        return regMap;
    }

    public static Properties getInstance() {
        if (null == properties) {
            properties = new Properties();
        }
        return properties;
    }

    public static Properties loadResource(String file) {
        properties = getInstance();
        try {
            InputStream inputStream = PropertiesUtil.class.getClassLoader().getResourceAsStream(file);
            System.out.println(inputStream);
            if (properties != null) {
                properties.load(inputStream);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return properties;
    }

    public static void main(String[] args) {
        PropertiesUtil pu = new PropertiesUtil("kafka/kafka.properties");
        Map<String, String> propsMap = pu.getProperties();

        for (Map.Entry<String, String> entry : propsMap.entrySet()) {
            System.out.println(("key: " + entry.getKey() + ", value: " + entry.getValue()));
        }


        Properties properties = loadResource("kafka/kafka.properties");
        System.out.println(properties.getProperty("kafka.producer.batch.size"));
        System.out.println("====================");
        System.out.println(PropertiesUtil.getInstance().getProperty("kafka.producer.batch.size"));
    }


}

